<template>
  <div>
    <q-table
      class="bg-white"
      dense
      :data="data"
      :columns="columns"
      row-key="id"
      separator="cell"
      selection="multiple"
      :selected.sync="selected"
      :visible-columns="visibleColumns"
      :filter="searchForm"
      :pagination.sync="pagination"
      :rows-per-page-options="[3, 5, 10, 20]"
      no-data-label="暂无数据"
      table-class="h-custom"
      @request="listGet"
    >
      <template v-slot:top-left="props">
        <q-btn size="sm" color="light-blue" :label="$t('新增')"  @click="add"/>
      </template>
      <template v-slot:top-right="props">
        <q-select
          v-model="visibleColumns"
          multiple
          borderless
          options-dense
          :display-value="$t('显示列')"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          class="q-mx-lg"
        >
          <template v-slot:option="scope">
            <q-item
              v-bind="scope.itemProps"
              v-on="scope.itemEvents"
              v-if="!scope.opt.required"
            >
              <q-item-section avatar>
                <q-toggle color="blue" v-model="visibleColumns" :val="scope.opt.name" />
              </q-item-section>
              <q-item-section style="min-width:60px">
                {{ scope.opt.label }}
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <q-toggle
          v-model="searchToggle"
          left-label
          label="搜索"
          color="blue"
          checked-icon="check"
          unchecked-icon="clear"
          keep-color
        />
        <q-btn
          flat round dense
          :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
          @click="props.toggleFullscreen"
          class="q-ml-md"
        />
      </template>
      <template v-slot:top-row="props" v-if="searchToggle">
        <q-tr :props="props">
          <q-td>
          </q-td>
          <q-td v-for="col in props.cols" :key="col.name" class="">
            <q-btn color="primary" dense flat  icon="search"  v-if="col.name==='action'"  @click="listGet({ pagination: pagination, filter: searchForm })"/>
            <q-input dense outlined v-model="searchForm[col.name]" v-else/>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th>
            <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
          </q-th>
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td>
            <q-checkbox dense v-model="props.selected" />
          </q-td>
          <q-td key="action" :props="props">
            <q-btn-dropdown
              color="blue"
              size="sm"
              dense
              menu-anchor="bottom left"
              menu-self="top left"
              content-class="text-grey"
              icon="settings">
              <q-list dense>
                <q-item clickable v-close-popup @click="edit(props.row)">
                  <q-item-section>
                    <q-item-label>修改</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup  @click="delRow(props.row)">
                  <q-item-section>
                    <q-item-label>删除</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup v-if="props.row.active === 0"  @click="active(props.row,actives = 1)">
                  <q-item-section>
                    <q-item-label>启用</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup v-if="props.row.active === 1"  @click="active(props.row,actives = 0)">
                  <q-item-section>
                    <q-item-label>禁用</q-item-label>
                  </q-item-section>
                </q-item>
                <!-- <q-item clickable v-close-popup @click="props.expand = !props.expand">
                  <q-item-section>
                    <q-item-label>{{ props.expand? '收起': '更多字段' }}</q-item-label>
                  </q-item-section>
                </q-item> -->
              </q-list>
            </q-btn-dropdown>
          </q-td>
          <q-td key="code" :props="props">
            {{ props.row.code }}
          </q-td>
          <q-td key="name" :props="props">{{ props.row.name }}</q-td>
          <q-td key="nameEn" :props="props">{{ props.row.nameEn }}</q-td>
          <q-td key="typeName" :props="props">{{ props.row.typeName }}</q-td>
          <q-td key="active" :props="props">
            <q-chip dense square label="启用" color="positive" text-color="white" v-if="props.row.active===1"/>
            <q-chip dense square label="禁用" color="negative" text-color="white" v-if="props.row.active===0"/>
          </q-td>
          <q-td key="prefix" :props="props">{{ props.row.prefix }}</q-td>
          <q-td key="suffix" :props="props">{{ props.row.suffix }}</q-td>
          <q-td key="minValue" :props="props">{{ props.row.minValue }}</q-td>
          <q-td key="startValue" :props="props">{{ props.row.startValue }}</q-td>
          <q-td key="maxValue" :props="props">{{ props.row.maxValue }}</q-td>
          <q-td key="incValue" :props="props">{{ props.row.incValue }}</q-td>
          <q-td key="timeFmt" :props="props">{{ props.row.timeFmt }}</q-td>
          <q-td key="remark" :props="props" class="h-td-maxwidth ellipsis">
            {{ props.row.remark }}
            <q-popup-edit v-model="props.row.remark">
              <q-input type="textarea" v-model="props.row.remark" readonly dense autofocus counter />
            </q-popup-edit>
          </q-td>
          <q-td key="createUserName" :props="props">{{ props.row.createUserName }}</q-td>
          <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
          </q-td>
        </q-tr>
      </template>
      <template v-slot:pagination="props">
        <q-pagination
          v-model="pagination.page"
          color="blue"
          :max-pages="5"
          :max="pages"
          :boundaryLinks="true"
          :directionLinks="true"
        />
        共 {{ total }} 条
      </template>
    </q-table>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '新增' : '修改'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div :class="$v.addOrEditForm.name.$error?'text-negative': ''">名称</div>
                <q-input
                v-model="addOrEditForm.name"
                error-message="该字段为必填项"
                :error="$v.addOrEditForm.name.$error"
                @blur="$v.addOrEditForm.name.$touch"
                dense hint/>
             </div>
            <div class="col-12">
              <div>英文名称</div>
                <q-input
                v-model="addOrEditForm.nameEn"
                dense hint/>
             </div>
            <div class="col-12">
              <div>所属类型</div>
              <q-select
                emit-value
                map-options
                dense
                v-model="addOrEditForm.typeCode"
                :options="codeOption" />
             </div>
            <div class="col-12">
              <div :class="$v.addOrEditForm.code.$error?'text-negative': ''">编码</div>
                <q-input
                error-message="该字段为必填项"
                :error="$v.addOrEditForm.code.$error"
                @blur="$v.addOrEditForm.code.$touch"
                v-model="addOrEditForm.code"
                dense hint/>
             </div>
            <div class="col-12">
              <div :class="$v.addOrEditForm.prefix.$error?'text-negative': ''">前缀</div>
                <q-input
                v-model="addOrEditForm.prefix"
                :error-message="$v.addOrEditForm.prefix.required ?'前缀不能是负数和中文字符':'该字段为必填项'"
                :error="$v.addOrEditForm.prefix.$error"
                @blur="$v.addOrEditForm.prefix.$touch"
                dense hint/>
             </div>
             <div class="col-12">
              <div :class="$v.addOrEditForm.suffix.$error?'text-negative': ''">后缀</div>
                <q-input
                v-model="addOrEditForm.suffix"
                :error-message="$v.addOrEditForm.suffix.required ?'该字段为必填项' : '后缀不能是负数和中文字符'"
                :error="$v.addOrEditForm.suffix.$error"
                @blur="$v.addOrEditForm.suffix.$touch"
                dense hint/>
             </div>
            <div class="col-12">
              <div :class="$v.addOrEditForm.minValue.$error?'text-negative': ''">最小值</div>
                <q-input
                type="number"
                v-model="addOrEditForm.minValue"
                :error-message="$v.addOrEditForm.minValue.required?'请填写正整数':'该字段为必填项'"
                :error="$v.addOrEditForm.minValue.$error"
                @blur="$v.addOrEditForm.minValue.$touch"
                dense hint/>
             </div>
            <div class="col-12">
              <div :class="$v.addOrEditForm.startValue.$error?'text-negative': ''">起始值</div>
                <q-input
                type="number"
                v-model="addOrEditForm.startValue"
                error-message="请填写正整数"
                :error="$v.addOrEditForm.startValue.$error"
                @blur="$v.addOrEditForm.startValue.$touch"
                dense hint/>
             </div>
            <div class="col-12">
              <div :class="$v.addOrEditForm.maxValue.$error?'text-negative': ''">最大值</div>
                <q-input
                type="number"
                v-model="addOrEditForm.maxValue"
                :error-message="$v.addOrEditForm.minValue.required?($v.addOrEditForm.minValue.max?'最大值要大于最小值':'请填写正整数'):'该字段为必填项'"
                :error="$v.addOrEditForm.maxValue.$error"
                @blur="$v.addOrEditForm.maxValue.$touch"
                dense hint/>
             </div>
            <div class="col-12">
              <div>递增值</div>
                <q-input
                v-model="addOrEditForm.incValue"
                dense hint/>
             </div>
            <div class="col-12">
              <div>是否包含时间</div>
              <q-select
                emit-value
                map-options
                dense
                v-model="addOrEditForm.includeTime"
                :options="typeOption" />
             </div>
            <div class="col-12"  v-if="addOrEditForm.includeTime==1">
              <div>时间格式</div>
              <q-select
                emit-value
                map-options
                dense
                v-model="addOrEditForm.timeFmt"
                :options="timeOption" />
             </div>
            <div class="col-12">
              <div>说明</div>
                <q-input
                maxlength="200"
                type="textarea"
                v-model="addOrEditForm.remark"
                dense hint/>
             </div>
          </div>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveHandler" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { plusInteger, isChinese } from 'src/utils/my.validators.js'
import { required } from 'vuelidate/lib/validators'
var max = function (value) {
  return plusInteger(value)
}
export default {
  name: 'CodeList',
  data () {
    return {
      addOrEdit: 1, // 1 新增  2 修改
      loadingSave: false,
      addOrEditDialog: false,
      maximizedToggle: false,
      searchToggle: false,
      searchForm: {
        name: '',
        code: '',
        nameEn: '',
        typeName: '',
        active: '',
        prefix: '',
        suffix: '',
        minValue: '',
        startValue: '',
        maxValue: '',
        incValue: '',
        timeFmt: '',
        remark: '',
        createUserName: '',
        createTime: ''
      },
      codeOption: [],
      addOrEditForm: {
        id: '',
        typeCode: '',
        name: '',
        nameEn: '',
        code: '',
        prefix: '',
        suffix: '',
        minValue: '1',
        startValue: '1',
        maxValue: '99999999',
        incValue: '1',
        // digit: '',
        includeTime: 0,
        timeFmt: '',
        remark: ''
      },
      typeOption: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      timeOption: [
        {
          label: 'yyyyMMdd',
          value: 'yyyyMMddHHmm'
        },
        {
          label: 'yyyyMMddHHmm',
          value: 'yyyyMMddHHmm'
        }
      ],
      selected: [],
      data: [],
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      visibleColumns: [
        'action',
        'name',
        'code',
        'nameEn',
        'typeName',
        'active',
        'prefix',
        'suffix',
        'minValue',
        'startValue',
        'maxValue',
        'incValue',
        'timeFmt',
        'remark',
        'createUserName',
        'createTime'
      ],
      columns: [
        { name: 'action', align: 'center', label: '操作' },
        { name: 'code', align: 'left', label: '编码', field: 'code', sortable: true },
        { name: 'name', align: 'left', label: '名称', field: 'name', sortable: true },
        { name: 'nameEn', align: 'left', label: '英文名称', field: 'nameEn', sortable: true },
        { name: 'typeName', align: 'left', label: '类型名称', field: 'typeName', sortable: true },
        { name: 'active', align: 'left', label: '状态', field: 'active', sortable: true },
        { name: 'prefix', align: 'left', label: '前缀', field: 'prefix', sortable: true },
        { name: 'suffix', align: 'left', label: '后缀', field: 'suffix', sortable: true },
        { name: 'minValue', align: 'left', label: '起始值', field: 'minValue', sortable: true },
        { name: 'startValue', align: 'left', label: '当前值', field: 'startValue', sortable: true },
        { name: 'maxValue', align: 'left', label: '最大值', field: 'maxValue', sortable: true },
        { name: 'incValue', align: 'left', label: '递增值', field: 'incValue', sortable: true },
        { name: 'timeFmt', align: 'left', label: '时间格式', field: 'timeFmt', sortable: true },
        { name: 'remark', align: 'left', label: '说明', field: 'remark', sortable: true },
        { name: 'createUserName', align: 'left', label: '创建人', field: 'createUserName', sortable: true },
        { name: 'createTime', align: 'left', label: '创建时间', field: 'createTime', sortable: true }
      ]
    }
  },
  validations: {
    addOrEditForm: {
      name: { required },
      prefix: {
        required,
        // max,
        isRule () {
          return !isChinese(this.addOrEditForm.prefix)
        }
        // char () {
        //   return !ischar(this.addOrEditForm.prefix)
        // }
      },
      suffix: {
        // max,
        isRule () {
          console.log(this.addOrEditForm.suffix)
          if (this.addOrEditForm.suffix !== null && this.addOrEditForm.suffix !== '') {
            return !isChinese(this.addOrEditForm.suffix)
          } else {
            console.log('我是空白')
            return true
          }
        }
      },
      code: { required },
      minValue: {
        required,
        max,
        new (val) {
          return Number(this.addOrEditForm.minValue) < Number(this.addOrEditForm.maxValue)
        }
      },
      startValue: {
        max
      },
      // digit: { max },
      incValue: { max },
      maxValue: {
        required,
        max,
        new (val) {
          return Number(this.addOrEditForm.maxValue) > Number(this.addOrEditForm.minValue)
        }
      }
    }
  },
  computed: {
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    }
  },
  watch: {
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    }
  },
  mounted () {
    this.init()
    this.getCodeType()
  },
  methods: {
    edit (prop) {
      this.addOrEdit = 2
      this.addOrEditForm = {
        id: prop.id,
        typeCode: prop.typeCode,
        name: prop.name,
        nameEn: prop.nameEn,
        code: prop.code,
        prefix: prop.prefix,
        suffix: prop.suffix,
        minValue: prop.minValue,
        startValue: prop.startValue,
        maxValue: prop.maxValue,
        incValue: prop.incValue,
        // digit: '',
        includeTime: prop.includeTime,
        timeFmt: prop.timeFmt,
        remark: prop.remark
      }
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    add () {
      this.addOrEdit = 1
      this.addOrEditTab = 'tab1'
      this.addOrEditForm = {
        id: '',
        typeCode: '',
        name: '',
        nameEn: '',
        code: '',
        prefix: '',
        suffix: '',
        minValue: '1',
        startValue: '1',
        maxValue: '99999999',
        incValue: '1',
        // digit: '',
        includeTime: 0,
        timeFmt: '',
        remark: ''
      }
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    init () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    async listGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/common/serial/query',
        params: {
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.total = data.total
          this.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.pagination.page = page
      this.pagination.rowsPerPage = rowsPerPage
      this.pagination.sortBy = sortBy
      this.pagination.descending = descending
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: this.addOrEdit === 1 ? '/common/serial/add' : '/common/serial/updateSerial',
          params: this.addOrEditForm,
          emulateJSON: true,
          useNotify: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
            this.listGet({
              pagination: this.pagination,
              filter: this.searchForm
            })
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
      } else {
        this.errorCopy = true
      }
    },
    active (row, actives) {
      let id = row.id
      let active = actives
      let arr = {}
      arr.id = id
      arr.active = active
      arr.typeCode = row.typeCode
      this.$q.dialog({
        message: `确认要启用/禁用：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'put',
          url: `/common/serial/update`,
          params: arr,
          emulateJSON: true,
          useNotify: true,
          successCallback: ({ data }) => {
            this.listGet({
              pagination: this.pagination,
              filter: this.searchForm
            })
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
      }).onCancel(() => {

      })
    },
    delRow (row) {
      this.$q.dialog({
        title: '删除',
        message: `确认要删除：${row.name} 吗？`,
        ok: true,
        cancel: true,
        persistent: true
      }).onOk(async () => {
        await this.$api({
          method: 'delete',
          url: `/common/serial/delete/${row.id}`,
          useLoadLayer: true,
          useNotify: true,
          successCallback: ({ data }) => {
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.listGet({
          pagination: this.pagination,
          filter: this.searchForm
        })
      }).onCancel(() => {

      })
    },
    // 获取编码类型
    async getCodeType () {
      await this.$api({
        method: 'post',
        url: '/common/dict/findByTypeCode/70',
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          let arr = []
          data.forEach(item => {
            let o = {}
            o.label = item.name
            o.value = item.code
            arr.push(o)
          })
          this.codeOption = arr
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
  .h-td-maxwidth
    max-width 150px
  // 去除table header checkbox 所在td的top border
  .q-table--cell-separator td, .q-table--cell-separator th
    border-width 1px
    border-top-width 0
  .expand-row-label
    display inline-block
    width 80px
    text-align left
</style>
